package cn.edu.zafu.bigdata.hdb;
import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        int port = 12345;    //服务端端口号
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("聊天服务端启动，等待连接。。。");
            //不断等待客户端连接
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接：" + clientSocket.getInetAddress());
                //创建线程处理每个客户端连接
                new Thread(new ClientHandler(clientSocket)).start();
            }
        }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
class   ClientHandler implements Runnable{
        private Socket socket;
        public ClientHandler(Socket socket){
            this.socket=socket;
        }
        @Override
        public void run(){
            try(BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(),true)) {
                String message;
                //持续接收客户端消息
                while ((message=in.readLine()) !=null){
                    System.out.println("收到来自客户端的消息："+message);
                    out.println("服务端回复："+message);//Echo back to client
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                try{
                    socket.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
}
